package com.ymcv.proyecto7.view;

import java.util.Timer;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ymcv.proyecto7.R;
import com.ymcv.proyecto7.controller.ServicioController;
import com.ymcv.proyecto7.controller.UsuarioController;
import com.ymcv.proyecto7.model.entity.Servicio;
import com.ymcv.proyecto7.model.entity.Usuario;
import com.ymcv.proyecto7.tools.Confirm;
import com.ymcv.proyecto7.tools.LocationTask;
import com.ymcv.proyecto7.tools.MyPagerAdapter;
import com.ymcv.proyecto7.view.Servicio_Fragment.OnServicioListener;

public class Principal_Activity extends FragmentActivity implements
		ActionBar.TabListener, LocationListener, LocationSource,
		OnServicioListener {

	MyPagerAdapter myPagerAdapter;
	ViewPager vpPagina;

	UsuarioController controller;
	Usuario usuario;
	ServicioController controllerS;
	Servicio servicio;

	Trafico_Fragment fraTrafico;
	Servicio_Fragment fraServicio;
	Cliente_Fragment fraCliente;

	ActionBar actionBar;

	Bundle args;
	IntentFilter filter;
	Push push;
	Timer timer;
	Actualizacion actualizacion;
	IntentFilter filterA;
	Reserva reserva;
	IntentFilter filterReserva;
	Contador tReserva;

	OnLocationChangedListener locListener;
	LocationManager manager;
	MarkerOptions marker;

	@Override
	protected void onCreate(Bundle b) {
		// TODO Auto-generated method stub
		super.onCreate(b);
		setContentView(R.layout.activity_principal);
		iniciarComponentes();
	}

	public void iniciarComponentes() {
		controller = new UsuarioController(this);
		usuario = controller.obtenerUsuario();
		controllerS = new ServicioController(this);
		servicio = new Servicio();

		fraServicio = new Servicio_Fragment();
		fraServicio.setOnServicioListener(this);
		fraCliente = new Cliente_Fragment();
		fraTrafico = Trafico_Fragment.getInstance();
		args = null;

		myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
		myPagerAdapter.setContext(getApplicationContext());
		myPagerAdapter.setFragments(fraServicio, fraCliente, fraTrafico);
		actionBar = getActionBar();
		actionBar.setHomeButtonEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		vpPagina = (ViewPager) findViewById(R.id.vpPagina);
		vpPagina.setAdapter(myPagerAdapter);
		vpPagina.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < myPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab()
					.setText(myPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			activarUpdates(LocationManager.NETWORK_PROVIDER);
		} else {
			activarUpdates(LocationManager.GPS_PROVIDER);
		}

		push = new Push();
		filter = new IntentFilter("GCM");
		actualizacion = new Actualizacion();
		filterA = new IntentFilter("location");
		reserva = new Reserva();
		filterReserva = new IntentFilter("reserva");
		registerReceiver(reserva, filterReserva);
		iniciarTimer();

	}

	public void activarUpdates(String provider) {
		Location loc = manager.getLastKnownLocation(provider);
		guardarMiUbicacion(loc);
		manager.requestLocationUpdates(provider, 3000, 1, this);
		// fraTrafico.mostrarMiUbicacion(new LatLng(loc.getLatitude(),
		// loc.getLongitude()));
	}

	public void guardarMiUbicacion(Location loc) {
		usuario.setLat(loc.getLatitude());
		usuario.setLon(loc.getLongitude());
		controller.actualizarPunto(usuario);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		try{unregisterReceiver(push);}catch(Exception e){}
		try {
			unregisterReceiver(actualizacion);
		} catch (Exception e) {
		}
		try {
			unregisterReceiver(reserva);
		} catch (Exception e) {
		}
		if (timer != null) {
			timer.cancel();
		}
		manager.removeUpdates(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerReceiver(push, filter);
		registerReceiver(actualizacion, filterA);
		manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000,
				1, this);
	}

	@Override
	public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction fm) {
		vpPagina.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
	}

	public void removerExtras() {
		this.getIntent().replaceExtras(new Bundle());
	}

	public void iniciarTimer() {
		registerReceiver(push, filter);
		registerReceiver(actualizacion, filterA);
		LocationTask task = new LocationTask(this);
		timer = new Timer();
		timer.schedule(task, 0, usuario.getPos_libre() * 60 * 1000);
	}

	public void terminarTimer() {
		timer.cancel();
		unregisterReceiver(push);
		unregisterReceiver(actualizacion);
	}

	@Override
	public void activate(OnLocationChangedListener listener) {
		// TODO Auto-generated method stub
		locListener = listener;
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
		locListener = null;
	}

	@Override
	public void onLocationChanged(Location loc) {
		Log.i("LatLon1", "Cambio");
		Log.i("LatLon1", "lat = " + loc.getLatitude());
		Log.i("LatLon1", "lon = " + loc.getLongitude());

		fraTrafico.mostrarMiUbicacion(new LatLng(loc.getLatitude(), loc
				.getLongitude()));
		guardarMiUbicacion(loc);
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onActualizar(View v) {
		if (getIntent().getExtras() != null) {
			if (!getIntent().getExtras().getBoolean("push")) {
				terminarTimer();
				iniciarTimer();
			}
		} else {
			terminarTimer();
			iniciarTimer();
		}
	}

	@Override
	public void onAceptar(View v) {
		tReserva.cancel();
		Confirm confirm = new Confirm(getApplicationContext());
		confirm.execute(usuario.getId_unidad() + "", getIntent().getExtras()
				.getString("tranid"), "si");
	}

	@Override
	public void onLLegadaPunto(View v) {
		// TODO Auto-generated method stub

	}

	public class Actualizacion extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Bundle b = intent.getExtras();
			if (b.getInt("intentos") == 0) {
				try {
					fraServicio.tvFechaAct.setText(b.getString("fecha"));
				} catch (Exception e) {

				}
			} else {
				int intentos = b.getInt("intentos");
				Log.i("Actualizacion", "Intento 1");
				if (intentos == 5) {
					timer.cancel();
					usuario = controller.obtenerUsuario();
					usuario.setIntentos(0);
					int i = controller.actualizarIntentos(usuario);
					Log.i("Actualizacion", "Cancelada!");
				}
			}
		}

	}

	public class Push extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			terminarTimer();
			args = intent.getExtras();
			args.putBoolean("push", true);
			getIntent().putExtras(args);
			actionBar.setSelectedNavigationItem(0);
			try {
				fraServicio.putPush(getIntent().getExtras());
				tReserva = new Contador(usuario.getAcepta_res() * 60 * 1000,
						1000);
				tReserva.start();
			} catch (Exception e) {
				Toast.makeText(context, "llego el push",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	public class Reserva extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getExtras().getBoolean("acept")) {
				actionBar.setSelectedNavigationItem(0);
				Bundle b = getIntent().getExtras();
				servicio.setTranid(Integer.parseInt(b.getString("tranid")));
				servicio.setNombre(b.getString("nombre"));
				servicio.setApellido(b.getString("apellido"));
				servicio.setRsocial(b.getString("rsocial"));
				servicio.setDirorigen(b.getString("dirorigen"));
				servicio.setLatorig(Double.parseDouble(b.getString("latorig")));
				servicio.setLonorig(Double.parseDouble(b.getString("lonorig")));
				servicio.setReforigen(b.getString("reforigen"));
				servicio.setDirorigen(b.getString("dirdestino"));
				servicio.setLatorig(Double.parseDouble(b.getString("latdest")));
				servicio.setLonorig(Double.parseDouble(b.getString("londest")));
				servicio.setReforigen(b.getString("refdestino"));

				servicio.setHoraserv(b.getString("horaserv"));

				controllerS.crear(servicio);

				removerExtras();
				fraServicio.removePush();
				fraServicio.cargarServicio();

				LocationTask task = new LocationTask(getApplicationContext());
				timer = new Timer();
				timer.schedule(task, 0, usuario.getSeg_res() * 60 * 1000);
			} else {
				removerExtras();
				iniciarTimer();
			}
			unregisterReceiver(reserva);
		}
	}

	public class Contador extends CountDownTimer {

		public Contador(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onTick(long millisUntilFinished) {
			// TODO Auto-generated method stub
			try {
				fraServicio.tiempoAcepta(millisUntilFinished);
			} catch (Exception e) {

			}
			Log.i("COUNT", "" + (millisUntilFinished) / 1000);
		}

		@Override
		public void onFinish() {
			actionBar.setSelectedNavigationItem(0);
			try {
				fraServicio.removePush();
			} catch (Exception e) {

			}
			try {
				fraTrafico.quitarPuntos();
			} catch (Exception e) {

			}
			Confirm confirm = new Confirm(getApplicationContext());
			confirm.execute(usuario.getId_unidad() + "", getIntent()
					.getExtras().getString("tranid"), "no");
			Log.i("COUNT", "finish");
		}
	}

}
